<template>
  <div class="app-container">
    <div class="ota-list">
      <div class="list-form">
        <el-form v-column="4" :model="dataFilter" ref="formRef">
          <el-form-item label="设备类型" prop="equipType">
              <el-select 
                v-model="dataFilter.equipType" 
                clearable
                placeholder="请选择"
              >
                <el-option 
                  v-for="item in equipOption"
                  :label="item.name" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>

          <el-form-item label="配置名称" prop="configName">
            <el-input v-model="dataFilter.configName" placeholder="请输入"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增配置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        :data="sourceData.list"
        highlight-current-row
        stripe
      >
        <el-table-column label="配置ID" prop="id" />
        <el-table-column label="配置名称" prop="configName" />
        <el-table-column label="配置文件" prop="originName" />
        <el-table-column label="设备数量" prop="equipNum" />
        <el-table-column label="状态" prop="status">
          <template #="{ row }">
            <el-tag v-if="row.status === 0" type="info">待开始</el-tag>
            <el-tag v-else-if="row.status === 1" type="warning">进行中</el-tag>
            <el-tag v-else-if="row.status === 2" type="success">已完成</el-tag>
            <el-tag v-else="row.status === 3" type="danger">未完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="操作" align="center" width="220">
          <template #="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              详情
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button type="primary" link @click="handleRetry(row)">
              重试
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleDell(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
    </div>
  </div>

  <RemoteDialog ref="dialog" @listChange="itemData" />
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { getDist, remoteDetail, remoteList, remoteRetry, remoteDell } from '@/api/collect'
import Pagination from '@/components/Pagination/Index.vue'
import RemoteDialog from './components/RemoteDialog.vue'
const formRef = ref<FormInstance>()
const dataFilter = reactive({
  equipType: '',
  configName: '',
})

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const equipOption = ref<any>([])

const getEquipList = () => {
  getDist('DC00011').then((res: any)=>{
    equipOption.value = res.data
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

getEquipList()

const sourceData = reactive({
  list: [] as any,
})

const getList = () => {
  remoteList({
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }).then((res)=>{
    console.log('res', res)
    sourceData.list = res.data.records
    // TODO use real api total res total
    pageProps.value.total = res.data.total
  })
  .catch((err) => {
    console.error('err', err)
  })
}

getList()

const onSearch = () => {
  getList()
}

const dialog: any = ref(null)

const handleAdd = () => {
  // dialog.value.reset()
  // console.log('tableItem', dialog.value.tableItem)
  dialog.value.dialogVisible = true
  dialog.value.isDisabled = true
  dialog.value.dialogStatus = 'create'
}

const router = useRouter()

const handleView = (row: any) => {
  router.push({
    name: 'RemoteDetail',
    query: {
      id: row.id,
    }
  })
}

const handleEdit = (row: any) => {
  dialog.value.dialogVisible = true
  dialog.value.dialogStatus = 'edit'
  nextTick(()=>{
    remoteDetail(row.id)
    .then((res)=>{
      console.log('res', res)
      dialog.value.isDisabled = true
      Object.assign(dialog.value.formItem, res.data)
      dialog.value.getEquipList()
      if (res.data.equipList) {
        setTimeout(()=>{
          dialog.value.tableData.list.push(...res.data.equipList)
          dialog.value.tableData.list.forEach((item: any, index: number) => {
            // TODO 
            // if (item.id == res.data.equipList[0].id) {
            //   dialog.value.tableRef.value!.toggleRowSelection(item)
            // }
          })
        }, 1000)
      }
      let uploadList = {
          name: res.data.originName,
          url: res.data.pkgUrl
      }
      dialog.value.formItem.uploadList.push(uploadList)
    })
    .catch((err)=>{
      console.error('err', err)
    })
  })
}

const itemData = () => {
  getList()
}

const handleRetry = (row: any) => {
  ElMessageBox.confirm(
    '确定要重试吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {  
    remoteRetry(row.id)
    .then((res: any) => {
      ElMessage.success('重试成功！')
      getList()
    })
    .catch((err: any) => {
      console.error('err', err.msg)
      ElMessage.error('重试失败！')
      getList()
    })
  })
  .catch(() => {})
}

const handleDell = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    const params = {
      idList: [row.id]
    }
    remoteDell(params)
    .then((res: any) => {
      ElMessage.success('删除成功！')
      getList()
    })
    .catch((err: any) => {
      console.error('err', err.msg)
      ElMessage.error('删除失败！')
      getList()
    })
  })
}

</script>

<style lang="scss" scoped>
.app-container {
  flex: 1;
  .ota-list {
    .list-form {
      padding: 24px 24px 0;
      background: #F5F7FA;
      margin-bottom: 24px;
      :deep(.el-form) {
        & > div:last-child > div {
          justify-content: flex-end;
        }
      }
    }
  }
}
</style>